package com.ruoyi.web.controller.system;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import cn.binarywang.wx.miniapp.bean.WxMaUserInfo;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.JsonUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.domain.ResponseDto;
import com.ruoyi.framework.web.service.MobileLoginService;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.system.domain.LoginParams;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.web.core.config.WxMaConfiguration;
import me.chanjar.weixin.common.error.WxErrorException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * 微信小程序用户接口
 *
 * @author gblfy
 * @date 2022-01-02
 */
@RestController
@RequestMapping("/login")
public class WxloginController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private ISysUserService userService;

    @Autowired(required = false)
    private MobileLoginService loginService;
    /**
     * 登陆接口
     */
    @GetMapping("/wxlogin")
    public AjaxResult login(@RequestParam String appid,
                            @RequestParam String code) {
        final WxMaService wxService = WxMaConfiguration.getMaService(appid);

        try {
            WxMaJscode2SessionResult session = wxService.getUserService().getSessionInfo(code);
           // this.logger.info(session.getSessionKey());
            //this.logger.info(session.getOpenid());
            System.out.println(session.getOpenid());
            SysUser user = new SysUser();
            user.setOpenid(session.getOpenid());
            List<SysUser> list = userService.selectMobileUserList(user);
            if(list==null || list.size()==0){
                // 新用户，需要插入数据库
                user.setNickName("新用户");
                user.setUserName(session.getOpenid());
                user.setCreateTime(new Date());
                user.setLoginDate(new Date());
                user.setPassword(session.getOpenid());
                user.setRoleId(2L);
                user.setSex(null);
                user.setCompany(" ");
                user.setBloodType(null);
                user.setIdCard(" ");

                user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
                boolean regFlag = userService.registerUser(user);
               list = userService.selectMobileUserList(user);
                user=list.get(0);
                user.setPassword(session.getOpenid());
            }else{
                SysUser oderUser = list.get(0);
                oderUser.setLoginDate(new Date());
                userService.updateUser(oderUser);
                BeanUtils.copyProperties(oderUser,user);
                if(oderUser.getPhonenumber()!=null && !"".equals(oderUser.getPhonenumber())){
                    user.setPassword(oderUser.getPhonenumber());
                    user.setUserName(oderUser.getUserName());
                }else {
                    user.setUserName(oderUser.getUserName());
                    user.setPassword(oderUser.getOpenid());
                    if(StringUtils.isEmpty(user.getPassword())){
                        user.setPassword(session.getOpenid());
                    }
                }
            }
            LoginParams loginParams = new LoginParams();
            loginParams.setUsername(user.getUserName());

            // 明文密码
            logger.info("用户："+user.getUserName()+"明文密码:"+user.getPassword());
            loginParams.setPassword(user.getPassword());
            loginParams.setLoginType("2");
            // 赋值普通角色
            Long[] roleIds=new Long[1];
            roleIds[0]=2L;
            userService.insertUserAuth(user.getUserId(), roleIds);
            AjaxResult ajax= loginService.login(loginParams);
            return ajax;
        } catch (Exception e) {
            this.logger.error(e.getMessage(), e);
             return AjaxResult.error("异常错误");
        }
    }
    @GetMapping("/info")
    public String info(@PathVariable String appid, String sessionKey,
                       String signature, String rawData, String encryptedData, String iv) {
        final WxMaService wxService = WxMaConfiguration.getMaService(appid);

        // 用户信息校验
        if (!wxService.getUserService().checkUserInfo(sessionKey, rawData, signature)) {
            return "user check failed";
        }

        // 解密用户信息
        WxMaUserInfo userInfo = wxService.getUserService().getUserInfo(sessionKey, encryptedData, iv);

        return JsonUtils.toJson(userInfo);
    }

    /**
     * <pre>
     * 获取用户绑定手机号信息
     * </pre>
     */
    @GetMapping("/phone")
    public String phone(@PathVariable String appid, String sessionKey, String signature,
                        String rawData, String encryptedData, String iv) {
        final WxMaService wxService = WxMaConfiguration.getMaService(appid);

        // 用户信息校验
        if (!wxService.getUserService().checkUserInfo(sessionKey, rawData, signature)) {
            return "user check failed";
        }

        // 解密
        WxMaPhoneNumberInfo phoneNoInfo = wxService.getUserService().getPhoneNoInfo(sessionKey, encryptedData, iv);

        return JsonUtils.toJson(phoneNoInfo);
    }

}
